<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP 4.3.2 or newer
 *
 * @package		CodeIgniter
 * @author		radio
 * @copyright	Copyright (c) 2008 - 2010, EllisLab, Inc.
 * @license		http://codeigniter.com/user_guide/license.html
 * @link		http://codeigniter.com
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	public  调试函数
 * @param	string	$string 打印的字符串
 * @param	bool	$is_die
 * @return	no return
 */
if ( ! function_exists('debug'))
{
	function debug($string,$is_die=true)
	{
	     echo '<pre>';
	     print_r($string);
	     if($is_die)die;
	}

}

// ------------------------------------------------------------------------

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	public
 * @param	string	$pagenum 总页数
 * @param	string	$curpage 当前页数
 * @param	string	$total	 总个数
 * @param	string	$baseurl 基础链接
 * @param	string	$segment 最多现示的数字个数
 * @return	no return
 */
if ( ! function_exists('pageEasy'))
{
	function pageEasy($pagenum=10,$curpage=0,$total=0,$baseurl='',$segment=5)
	{
		$CI =& get_instance();
		$CI->load->library('pagination');
     	$config['base_url'] = $baseurl;
    	$config['total_rows'] = $total;
    	$config['per_page'] = $pagenum;
	    $config['cur_page'] = $curpage*$pagenum;
	    $config['uri_segment'] = $segment;
	    $config['full_tag_open'] = '<div class="pagination">';
    	$config['full_tag_close'] = '</div>';   
    	$config['first_link'] = '首页'; 
    	$config['last_link'] = '尾页';
    	$config['next_link'] = '下一页';
    	$config['prev_link'] = '上一页';
	    $CI->pagination->initialize($config);
	}

}


// ------------------------------------------------------------------------

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	public
 * @param	string	$field_name 文件域
 * @param	string	$id ID
 * @return	no return
 */
if ( ! function_exists('uploadEasy'))
{
	function uploadEasy($field_name='',$cid=0,$new_dir='category/',$is_rename=true,$newname='')
	{	
		global $_FILES;
		$CI =& get_instance();
		$config['upload_path'] = $CI->config->item('upload_url').$new_dir;
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size'] = '2000';
		$config['max_width']  = '1024';
		$config['max_height']  = '768';
		$config['overwrite']  = true;
		$ext = explode('.',$_FILES[$field_name]['name']);
		if($is_rename)
		{
			if($newname)
			{
				$config['file_name']  = $newname.'.'.end($ext);
			}
			else 
			{
				$config['file_name']  = 'category_'.$cid.'.'.end($ext);
			}
		}
		else 
		{
			$config['file_name']  = $_FILES[$field_name]['name'];
		}
		$CI->load->library('upload', $config);
		 if(empty($cid))
		 {
		 	return '';
		 }
		  elseif ( ! $CI->upload->do_upload($field_name))
		  {
			   $error = array('error' => $CI->upload->display_errors());
			   return '';
		  } 
		  else
		  {
		  		$data = array('upload_data' => $CI->upload->data());
		  		return $config['upload_path'].$config['file_name'];
		  }
		  return '';
	}

}


// ------------------------------------------------------------------------

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	public	$string 展示相应类型的表单 用于系统设置
 * @return	return string
 */
if ( ! function_exists('showForm'))
{
	function showForm($v)
	{			
	     switch ($v['option_type'])
	     {
	     	case 'string':
			  $html = "<input type='text' class='text-input medium-input' value='$v[value]' name='$v[name]'/>";
			  break;  
		  	case 'number':
			  $html = "<input type='text' class='text-input medium-input' value='$v[value]' name='$v[name]'/>";
			  break;  
		  	case 'bool':
		  		$y = $n = '';
		  		if($v['value']=='Y')$y = "checked='checked'";
		  		if($v['value']=='N')$n = "checked='checked'";
			  $html = "<input type='radio' class='input' ".$y." value='Y' name='$v[name]'/>是"."<input type='radio' class='input' ".$n." value='N' name='$v[name]'/>否";
			  break;  
			case 'textarea':
			  $html = "<textarea class='text-input medium-input' name='$v[name]'>$v[value]</textarea>";
			  break;
			default:
				$html = '';
			  break;
	     }
	     return $html;
	}

}


// ------------------------------------------------------------------------

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	public  获得分类名
 * @return	return  string
 */
if ( ! function_exists('getCateName'))
{
	function getCateName($id=0)
	{
	    $CI =& get_instance();
		$CI->db->where('id',$id);
		$query = $CI->db->get('category','cname');
		$cname = $query->row_array();
		$cname = $cname['cname'];
		return $cname;
	}

}

// ------------------------------------------------------------------------

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	public  获得平台名
 * @return	return  string
 */
if ( ! function_exists('getPlatformName'))
{
	function getPlatformName($id=0)
	{
		$CI =& get_instance();
		$CI->db->where('id',$id);
		$query = $CI->db->get('platform','pname');
		$pname = $query->row_array();
		$pname = $pname['pname'];
		return $pname;
	}

}


// ------------------------------------------------------------------------

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	public  获得品牌名
 * @return	return  string
 */
if ( ! function_exists('getBrandName'))
{
	function getBrandName($id=0)
	{
		$CI =& get_instance();
		$CI->db->where('id',$id);
		$query = $CI->db->get('brand','bname');
		$bname = $query->row_array();
		$bname = $bname['bname'];
		return $bname;
	}

}

// ------------------------------------------------------------------------

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	public  获得应用名
 * @return	return  string
 */
if ( ! function_exists('getAppName'))
{
	function getAppName($id=0)
	{
		$CI =& get_instance();
		$CI->db->where('id',$id);
		$query = $CI->db->get('app','title');
		$title = $query->row_array();
		$title = $title['title'];
		return $title;
	}

}

// ------------------------------------------------------------------------

/**
 * 信息提示方式：1
 * 带多行导航链接,不带自动跳转.
 *
 * @param string $message
 * @param array $gotos
 * @example show_message1("你没有访问权限", array('uri'=>'admin/article', 'label'=>'查看文章'));
 */
if ( ! function_exists('show_message1'))
{
	function show_message1($message)
	{
		ob_start();
	    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	    header("Cache-Control: no-cache, must-revalidate");
	    header("Pragma: no-cache");
	    $args = func_get_args();
	    array_shift($args);
	    $CI = get_instance();
	    $data['gotos']   = $args;
	    $data['message'] = (string)$message;
	    $CI->load->view('_show_message1', $data);
		exit();
	}
}

// ------------------------------------------------------------------------

/**
 * 信息提示方式：2
 * 带自动跳转
 *
 * @param string $message  信息
 * @param string $goto	        地址
 * @param string $second   秒(缺省2秒)
 */
if ( ! function_exists('show_message2'))
{
	function show_message2($message, $goto, $second=1)
	{
	    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	    header("Cache-Control: no-cache, must-revalidate");
	    header("Pragma: no-cache");
	    $CI = get_instance();
	    $data['goto']    = (string)$goto;
	    $data['message'] = (string)$message;
	    $data['second'] = (int)$second;
	    $CI->load->view('_show_message2', $data);
	}
}

// ------------------------------------------------------------------------

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	public  后台提示信息函数
 */
if ( ! function_exists('showmessage'))
{
	function showmessage($message='', $url_forward='', $is_jump=1, $second=3) {
		$CI =& get_instance();
		//显示
		if($is_jump && $url_forward && empty($second)) 
		{
			header("HTTP/1.1 301 Moved Permanently");
			header("Location: $url_forward");
		} 
		else 
		{
				if($is_jump)
				{
					if($url_forward) {
					$message = "<a href=\"$url_forward\">$message</a><script>setTimeout(\"window.location.href ='$url_forward';\", ".($second*1000).");</script>";
					}
					$data['message'] = $message;
					$data['url_forward'] = $url_forward;
					$html = $CI->load->view('showmessage',$data,true);
					echo($html);die;
				}
				else {
					redirect("$url_forward.$message");
				}
		}
		exit();
	}
}

// ------------------------------------------------------------------------

/**
 * Parse out the attributes
 *
 * Some of the functions use this
 *
 * @access	public  前台提示信息函数
 */
if ( ! function_exists('showmsg'))
{
	function showmsg($message='', $url_forward='', $is_jump=1, $second=2) {
		$CI =& get_instance();
		//显示
		if($is_jump && $url_forward && empty($second)) 
		{
			header("HTTP/1.1 301 Moved Permanently");
			header("Location: $url_forward");
		} 
		else 
		{
				if($is_jump)
				{
					if($url_forward) {
					$message = "<a href=\"$url_forward\">$message</a><script>setTimeout(\"window.location.href ='$url_forward';\", ".($second*1000).");</script>";
					}
					$data['message'] = $message;
					$data['url_forward'] = $url_forward;
					$html = $CI->load->view('showmsg',$data,true);
					echo($html);die;
				}
				else {
					redirect("$url_forward.$message");
				}
		}
		exit();
	}
}
/**
 * 截取UTF-8编码下字符串的函数
 *
 * @param   string      $str        被截取的字符串
 * @param   int         $length     截取的长度
 * @param   bool        $append     是否附加省略号
 *
 * @return  string
 */ 
if(!function_exists('sub_str')) {
        function sub_str($str, $length = 0, $append = true)
        {
            $str = trim($str);
            $strlength = strlen($str);
        
            if ($length == 0 || $length >= $strlength)
            {
                return $str;
            }
            elseif ($length < 0)
            {
                $length = $strlength + $length;
                if ($length < 0)
                {
                    $length = $strlength;
                }
            }
        
            if (function_exists('mb_substr'))
            {
                $newstr = mb_substr($str, 0, $length, 'utf-8');
            }
            elseif (function_exists('iconv_substr'))
            {
                $newstr = iconv_substr($str, 0, $length, 'utf-8');
            }
            else
            {
                $newstr = substr($str, 0, $length);
            }
        
            if ($append && $str != $newstr)
            {
                $newstr .= '...';
            }
        
            return $newstr;
        }
}
 

/**
 * 获取用户ip
 *
 *
 * @return  string
 */ 
if(!function_exists('getIp')) {
	function getIp(){
	 if(!empty($_SERVER["HTTP_CLIENT_IP"])){
	  $cip = $_SERVER["HTTP_CLIENT_IP"];
	 }
	 elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
	  $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
	 }
	 elseif(!empty($_SERVER["REMOTE_ADDR"])){
	  $cip = $_SERVER["REMOTE_ADDR"];
	 }
	 else{
	  $cip = "无法获取！";
	 }
	 return $cip;
	}
}

/**
 * 发送email
 * @return  string
 */ 
if(!function_exists('sendEmail')) {
	function sendEmail($email,$subject,$content){
		$CI =& get_instance();
		$CI->load->helpers('email');
		$CI->load->library('email');
		if (!valid_email($email))
		{
			showmessage('对不起，邮件格式错误，请检查。',$_SERVER['HTTP_REFERER']);
		}
	 	$config['protocol'] = 'smtp';
//		$config['smtp_host'] = 'ssl://smtp.gmail.com';
		$config['smtp_user'] = 'zhangliutao2006@163.com';
		$config['smtp_pass'] = 's5924liutao';
		$config['smtp_host'] = 'smtp.163.com';
		$config['smtp_port'] = '25';
		$config['smtp_timeout'] = '5';
		$config['newline'] = "\r\n";
		$config['crlf'] = "\r\n";
		$config['crlf'] = "\r\n";
		$config['mailtype'] = 'html';
//		$config['charset'] = 'gb2312';
		$CI->email->initialize($config);//初始化邮件配置信息
		$CI->email->from('zhangliutao2006@163.com', 'appstore');
		$CI->email->to($email);
		$CI->email->subject($subject);
		$CI->email->message($content);
//		debug($CI->email);
		$return = $CI->email->send();
		return $return;
	}
}

/**
 * 检查是否登录 
 * @return  uid
 */ 
if(!function_exists('checklogin')) {	
	function checklogin()
	{
		include FCPATH.'./uc_client/client.php';
		
		if(!empty($_COOKIE['app_auth'])) {
			list($uid, $username) = explode("\t", uc_authcode($_COOKIE['app_auth'], 'DECODE'));
		} else {
			$uid = $username = '';
		}
		$user = array($uid,$username);
		return $user;
	}
}


/**
 * 获取广告html主体
 * @return  Array
 */ 
if(!function_exists('getAds')) {	
	function getAds($name,$pid=0)
	{
		$content = '';
		if(empty($pid))$pid = 0;
		if(!$name)
		{
			return FALSE;
		}
		else 
		{
			$CI =& get_instance();
			$pre = $CI->db->dbprefix;
			$query = $CI->db->query("select * from $pre"."ad where name='$name' and find_in_set('$pid',pid) order by `order` desc");
			$ad = $query->result_array();			
		}
		return $ad;
	}
}

/**
 * 获取广告html主体
 * @return  html
 */ 
if(!function_exists('getAd')) {	
	function getAd($name,$pid=0)
	{
		$content = '';
		if(empty($pid))$pid = 0;
		if(!$name)
		{
			echo ('广告id参数错误');
		}
		else 
		{
			$CI =& get_instance();
			$pre = $CI->db->dbprefix;
			$query = $CI->db->query("select * from $pre"."ad where name='$name' and find_in_set('$pid',pid)");
			$ad = $query->row_array();
			$content =  $ad['content'];
		}
		return $content;
	}
}

/**
 * 获取焦点图列表数据 
 * @return  图片array
 */ 
if(!function_exists('getFocusPic')) {	
	function getFocusPic($pid=0,$num=3)
	{
		if(empty($pid))$pid = 0;
		$CI =& get_instance();
		$pre = $CI->db->dbprefix;
		$query = $CI->db->query("select * from $pre"."focuspic where pid='$pid' order by `order` asc limit 0,$num");
		return $query->result_array();
	}
}


/**
 * yanzheng shifou youxiang 
 * @return  bool
 */ 
if(!function_exists('checkEmail')) {	
	function checkEmail($email)
	{
		return preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
	}
}

if(!function_exists('checkMobile')) {
	function checkMobile($str)
	{
		return (preg_match("/^13[0-9]{9}$|15[0-9]{9}$|18[0-9]{9}$/",$str))?true:false;
	}
}

if(!function_exists('checkRegisterName')) {
	function checkRegisterName($str)
	{
		return (preg_match("/^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/",$str))?true:false;
	}
}

if(!function_exists('checkPassword')) {
	function checkPassword($str)
	{
		return (preg_match("/^(\w){6,20}$/",$str))?true:false;
	}
}

/**
 * @return  bool
 */ 
if(!function_exists('getDomain')) {	
	function getDomain()
	{
		$domail = explode('/',base_url());
		return $domail[2];
	}
}


/**
 * @return  bool
 */ 
if(!function_exists('getUser')) {	
	function getUser($id)
	{
		$CI =& get_instance();
		$CI->db->where('uid',$id);
		$query = $CI->db->get('members');
		return $query->row_array();
	}
}

/**
 * @return  bool
 */ 
if(!function_exists('getAppId')) {	
	function getAppId($appname)
	{
		$CI =& get_instance();
		$CI->db->where('title',$appname);
		$query = $CI->db->get('app');
		$app = $query->row_array();
		return $app['id'];
	}
}

/**
 * @return  bool
 */ 
if(!function_exists('getUserId')) {	
	function getUserId($username)
	{
		$CI =& get_instance();
		$CI->db->where('username',$username);
		$query = $CI->db->get('members');
		$user = $query->row_array();
		return $user['uid'];
	}
}

/**
 * @return  bool
 */ 
if(!function_exists('data_china')) {	
	function data_china($data)
	{
		$data = $data + 8*3600;
		return date('Y-m-d H:i:s',$data);
	}
}

/**
 * 敏感词检测
 * @return  bool
 */ 
if(!function_exists('textfilter')) {	
	function textfilter($text)
	{
		$CI =& get_instance();
		$wordcensor = $CI->config->item("wordcensor");
		$words = explode(',',$wordcensor);
		if(is_array($words))
		{
			foreach ($words as $key=>$value)
			{
				if(strpos($text,$value)!=null || strpos($text,$value)===0)
				{
					return array('bool'=>false,'message'=>'您的语句中包含以下敏感词：'.$value);
				}
			}
		}
		return array('bool'=>true);
	}
}

/**
 * 热门关键词的获取和排序 来源于设置的和搜索的 两种关键词 
 * @return  array
 */ 
if(!function_exists('getSearchWords')) {	
	function getSearchWords()
	{
		$CI =& get_instance();
		$CI->load->model('search_words/words_model');
		$hotlist = $CI->words_model->getList('hot');
		$searchlist = $CI->words_model->getList('search',array('start'=>0,'end'=>10),array('order'=>'search_num','by'=>'desc'));
//		debug($searchlist);

		foreach ($searchlist as $key=>$value)
		{
			$midlist1[$key]=$value['word'];
		}
		foreach ($hotlist as $key=>$value)
		{
			$midlist2[$value['order']]=$value['word'];
		}
		$keys = array_keys($midlist2);
		foreach ($midlist1 as $key=>$value)
		{
			if(!in_array($key,$keys)&&!in_array($value,$midlist2))$midlist2[$key]=$midlist1[$key];
		}
		ksort($midlist2);
//		debug($midlist2);
		
		return $midlist2;
	}
}

/**
 * 搜索引擎调用接口
 * @return  array
 */ 
if(!function_exists('api_search')) {	
	function api_search($config_api_search='',$args=array())
	{
		//file_put_contents('log.txt',var_export($args,1),FILE_APPEND);
		$CI =& get_instance();
		$CI->load->library('Http');
		$jsonlist = $CI->http->post($config_api_search,$args);
		$returndata = json_decode($jsonlist,true);
		return $returndata;
	}
}

/**
 * 同步发布开放平台接口
 * @param  $mes 发布的文字信息
 */ 
if(!function_exists('api_oauth_post')) {	
	function api_oauth_post($mes='')
	{
		$CI =& get_instance();
		$userid = $CI->userid;
		$CI->load->model('opent');
		$CI->load->model('opent/opent_model',t_model);
		$list = $CI->t_model->fetchAll($userid);
		
		foreach ($list as $key=>$value)
		{
			if($value['is_sync'])//如果同步则发送相关信息
			{
				$function = 'sendMes'.$value['platform'];//获得平台发送信息函数
				if($_SESSION['last_key_'.$value['platform']]&&in_array($function,get_class_methods($CI->opent)))
				{
					@$CI->opent->$function($mes);
				}
			}
		}
		//以上循环发送各个平台的信息
	}
}

function getUserSid($model_id = '')
{
	$CI =& get_instance();
	$CI->load->model("cellphone");
	$modelinfo = $CI->cellphone->get_model_info($model_id);
	if(!$modelinfo)
	{
		return "";
	}
	$args_sid = $modelinfo['sid'];
	//通过机型适配时 为了java 和 android 做特殊处理
	if($modelinfo['pname']=='Java')
	{
		$args_sid = $modelinfo['sid'].',59';
	}
	elseif($modelinfo['pname']=='Android')
	{
		$args_sid = '';
	}
	elseif($modelinfo['pname']=='iPhone')
	{
		$args_sid = '';
	}
	elseif($modelinfo['pname']=='Symbian')
	{
		if(in_array($modelinfo['sid'],array(65,66,69,70)))$args_sid = $modelinfo['sid'].',71';
	}
	return $args_sid;
}

function wapgo($mes='',$url='',$sec=3)
{
	$CI =& get_instance();
	echo'<?xml version="1.0" encoding="utf-8"?>';
	$data['mes'] = empty($mes) ? '' : $mes;
	$data['url'] = empty($url) ? site_url('wap/index') : $url;
	$data['sec'] = empty($sec) ? 0 : $sec;
	$data['title'] = $CI->config->item('cfg_site_name');
	$html = $CI->load->view("wap/wapgo",$data,true);
	echo $html;exit();
}

/* End of file extra_helper.php */
/* Location: ./application/helpers/extra_helper.php */